package cn.edu.web;

import cn.edu.pojo.User;
import cn.edu.service.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;

/**
 * @author Davey chan
 */
@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
    private UserService service=new UserService();
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//        获取用户名和密码
        String username = request.getParameter("username");
        String password= request.getParameter("password");
        String remember= request.getParameter("remember");
//        调用service
        User user = service.login(username, password);
//        3，判断
        if(user !=null){
//            登录成功，重定向到Brand的SelectAll()
//            判断是否选择了记住我
            if("1".equals(remember)){
//                创建cookie
                Cookie c_username=new Cookie("username",username);
                Cookie c_password=new Cookie("password",password);
//                设置存活时间
                c_password.setMaxAge(60*60*24);
                c_username.setMaxAge(60*60*24);
//                发送cookie
                response.addCookie(c_password);
                response.addCookie(c_username);
            }
//            一次会话，有两次请求，将登录成功后的user对象存储到session中
            HttpSession session = request.getSession();
            session.setAttribute("user",user);//键值对
//            动态生成虚拟目录
            String contextPath = request.getContextPath();
            response.sendRedirect(contextPath+"/selectAllServlet");
        }else{
//            登陆失败
//存储错误信息到request中
            request.setAttribute("login_msg","用户名或者密码错误");
//          登录失败还接着跳转到login.jsp
            request.getRequestDispatcher("/login.jsp").forward(request,response);


        }
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }


}
